package com.angel.mongodb.annotation;

import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

/**
 * 查询媒介
 * 1. equals：相等
 * 2. like:mongodb的like查询
 * 3. in:用于列表的in类型查询
 */
public enum SortType {
    ASC {
        @Override
        public Sort buildSort(SortField sortFieldAnnotation, Field field) {
            if (check(sortFieldAnnotation, field)) {
                String sortField = getSortFieldName(sortFieldAnnotation, field);
                return Sort.by(Sort.Direction.ASC, sortField);
            }
            return Sort.unsorted();
        }
    },
    DESC {
        @Override
        public Sort buildSort(SortField sortFieldAnnotation, Field field) {
            if (check(sortFieldAnnotation, field)) {
                String sortField = getSortFieldName(sortFieldAnnotation, field);
                return Sort.by(Sort.Direction.DESC, sortField);
            }
            return Sort.unsorted();
        }
    };

    private static boolean check(SortField sortField, Field field) {
        return !(sortField == null || field == null);
    }

    public abstract Sort buildSort(SortField sortFieldAnnotation, Field field);


    /**
     * 如果实体bean的字段上SortField注解没有设置attribute属性时，默认为该字段的名称
     *
     * @param field
     * @return
     */
    private static String getSortFieldName(SortField sortField, Field field) {
        String sortFieldValue = sortField.attribute();
        if (!StringUtils.hasText(sortFieldValue)) {
            sortFieldValue = field.getName();
        }
        return sortFieldValue;
    }
}

